﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Diagnostics;
using WSShell = IWshRuntimeLibrary.WshShell;
using WSShortcut = IWshRuntimeLibrary.IWshShortcut;

using System.Drawing.Drawing2D;

namespace AppVImport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            DirectoryInfo dRoot = new DirectoryInfo(toolStripTextBox1.Text);
            List<AppvApps> sList = new List<AppvApps>();
            foreach (FileInfo fOSD in dRoot.GetFiles("*.osd", SearchOption.AllDirectories ))
            {
                AppvApps oApps = new AppvApps();

                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(fOSD.FullName);

                string sName = xDoc.SelectSingleNode(@"SOFTPKG/@NAME").InnerText;
                oApps.ProductName = xDoc.SelectSingleNode(@"SOFTPKG/@NAME").InnerText;
                oApps.Version = xDoc.SelectSingleNode(@"SOFTPKG/@VERSION").InnerText;
                oApps.GUID = xDoc.SelectSingleNode(@"SOFTPKG/@GUID").InnerText;
                oApps.SFTPath = xDoc.SelectSingleNode(@"SOFTPKG/IMPLEMENTATION/CODEBASE/@HREF").InnerText;
                oApps.LocalPath = fOSD.FullName;
                oApps.OSDPath = fOSD.FullName;
                try
                {
                    string sIcon = xDoc.SelectSingleNode(@"SOFTPKG/MGMT_SHORTCUTLIST/SHORTCUT/@ICON").InnerText.Replace("%SFT_MIME_SOURCE%", "");
                    sIcon = sIcon.Replace('/', '\\');
                    oApps.IconPath = fOSD.DirectoryName + sIcon;

                    Bitmap bmp = new Bitmap(16, 16);
                    //create a new graphic from the Bitmap
                    Graphics graphic = Graphics.FromImage((Image)bmp);
                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    //draw the newly resized image
                    graphic.DrawImage(Image.FromFile(oApps.IconPath), 0, 0, 16, 16);
                    graphic.Dispose();

                    oApps.icon = (Image)bmp;
                }
                catch(Exception ex)
                {
                    ex.Message.ToString();
                }

                if (!oApps.SFTPath.StartsWith(fOSD.DirectoryName))
                {
                    string sftpath = oApps.SFTPath.Replace('/', '\\');
                    sftpath = sftpath.Substring(sftpath.LastIndexOf('\\')+1);
                    sftpath.ToString();
                    if(File.Exists(Path.Combine(fOSD.DirectoryName, sftpath)))
                    {
                        oApps.SFTPath = Path.Combine(fOSD.DirectoryName, sftpath);
                    }
                    
                }

                sList.Add(oApps);



                if (xDoc.SelectSingleNode(@"SOFTPKG/IMPLEMENTATION/CODEBASE/@HREF").InnerText != oApps.SFTPath)
                {
                    xDoc.SelectSingleNode(@"SOFTPKG/IMPLEMENTATION/CODEBASE").Attributes["HREF"].Value = oApps.SFTPath;
                    xDoc.Save(fOSD.FullName);
                }
            }

            olvAppv.SetObjects(sList, true);
            olvAppv.AutoResizeColumns();
            
        }

        private void olvAppv_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
            foreach (BrightIdeasSoftware.OLVListItem oLVI in olvAppv.SelectedItems)
            {
                AppvApps oApp = oLVI.RowObject as AppvApps;

                try
                {
                    Process myProcess = new Process();

                    myProcess.StartInfo.UseShellExecute = false;
                    myProcess.StartInfo.FileName = "SFTTray.exe";
                    myProcess.StartInfo.Arguments = string.Format("/load \"{0}\" /sftfile \"{1}\" /hide", oApp.OSDPath, oApp.SFTPath);
                    myProcess.StartInfo.CreateNoWindow = true;
                    myProcess.Start();

                    appShortcutToDesktop(oApp.ProductName, string.Format("/launch \"{0}\"", oApp.ProductName), "App-V", oApp.IconPath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Unable to load App-V package...", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }


        }

        private void appShortcutToDesktop(string LinkName, string Arguments, string Description, string IconPath )
        {
            string LNKF = System.Environment.GetFolderPath(System.Environment.SpecialFolder.DesktopDirectory) + "\\" + LinkName + ".lnk";
            WSShell wsho = new WSShell();
            WSShortcut sc = (WSShortcut)wsho.CreateShortcut(LNKF);
            sc.TargetPath = "SFTTray.exe";
            sc.Arguments = Arguments;
            sc.Description = Description;
            sc.WorkingDirectory = Application.ProductName;
            sc.IconLocation = IconPath;
            sc.Save();

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripTextBox1.Text = Application.StartupPath;
            if (!string.IsNullOrEmpty(Properties.Settings.Default.ImportPath))
            {
                toolStripTextBox1.Text = Properties.Settings.Default.ImportPath;
            }

            toolStripButton1_Click(sender, e);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                toolStripTextBox1.Text = folderBrowserDialog1.SelectedPath;
                toolStripButton1_Click(sender, e);
            }
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (olvAppv.SelectedItems.Count == 0)
            {
                installApplicationToolStripMenuItem.Enabled = false;
            }
            else
            {
                installApplicationToolStripMenuItem.Enabled = true;
            }
        }

        private void installApplicationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            olvAppv_MouseDoubleClick(sender, null);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(linkLabel1.Tag.ToString());
        }

    }

    public class AppvApps
    {
        private string localpath;
        public string ProductName { get; set; }
        public string GUID { get; set; }
        public string Version { get; set; }
        public string SFTPath { get; set; }
        public string OSDPath { get; set; }
        public string IconPath { get; set; }
        public string LocalPath
        {
            get
            {
                return localpath;
            }

            set
            {
                try
                {
                    FileInfo fFile = new FileInfo(value);
                    //string sFile = SFTPath.Substring(SFTPath.LastIndexOf('/')).Replace("/","");
                    if (SFTPath.Contains("%SFT_SOFTGRIDSERVER%"))
                        SFTPath = SFTPath.Replace("%SFT_SOFTGRIDSERVER%", "LOCALHOST");
                    Uri uriAddress2 = new Uri(SFTPath);

                    string sFile = uriAddress2.LocalPath.Substring(uriAddress2.LocalPath.LastIndexOf('/')).Replace("/", "");
                    if (File.Exists(Path.Combine(fFile.DirectoryName, sFile)))
                    {
                        SFTPath = Path.Combine(fFile.DirectoryName, sFile);
                    }
                }
                catch { }

                localpath = value;
            }

        }
        public Image icon { get; set; }

    }
}
